<template>
  <div>
    <div v-if="modal&&visible" class="modal"></div>
    <div class="ms-drawer"
         :style="{width: fillScreen?'100%':width,right:visible?0:(fillScreen?'-100%':('-'+width)),zIndex:msIndex}">
      <div class="md-drawer" v-if="visible">
        <!--关闭按钮-->
        <div class="close">
          <template v-if="resize">
            <i class="el-icon-full-screen" v-if="!fillScreen" @click="fillScreen=true"></i>
            <i class="el-icon-copy-document" v-if="fillScreen" @click="fillScreen=false"></i>
          </template>
          <i class="el-icon-close" @click="clickClose"></i>
        </div>
        <!--头部-->
        <div class="md-header">
          <!--导航标签-->
          <div class="md-tags">
            <el-tabs v-model="activeName"
                     v-if="tabList.length>0"
                     :closable="tabList.length!==1"
                     type="card"
                     @tab-remove="removeTab">
              <template v-for="item in tabList">
                <el-tab-pane :name="item.row[idKey]+'-'+item.component"
                          :key="item.component"
                             :label="(item.type==='open'?'创建':(item.type==='edit'?'编辑':'查看'))+item.title">
                </el-tab-pane>
              </template>
            </el-tabs>
            <slot v-else name="title">{{ title }}</slot>
          </div>
        </div>
        <!--内容区域-->
        <div class="md-container">
          <template  v-if="tabList.length>0" v-for="item in tabList">
            <component v-show="(item.row[idKey]+'-'+item.component) === activeName"
                       :showThisTabs="(item.row[idKey]+'-'+item.component) === activeName"
                       :key="(item.row[idKey]+'-'+item.component)"
                       ref="com"
                       :type="item.type"
                       :data="item.row"
                       @refresh="$emit('refresh')"
                       @close="clickClose"
                       @viewToEdit="viewToEdit(item)"
                       @removeThisTabs="removeThisTabs(item)"
                       :is="item.component">
            </component>
          </template>
          <slot v-else></slot>
        </div>
        <!--按钮组-->
        <div class="md-btns" style="text-align: right">
          <slot name="footer"></slot>
        </div>
      </div>
    </div>
  </div>

</template>
<script>
import EnumManageTemp from "@/views/DMDEnumManage/enumManageTemp.vue";
import UnitsManageTemp from "@/views/DMDUnitsManage/unitsManageTemp.vue";
import PropertiesClassifyTemp from "@/views/DMDPropertiesClassify/PropertiesClassifyTemp.vue";
import PropertiesDefinedTemp from "@/views/DMDPropertiesDefined/PropertiesDefinedTemp.vue";
import CommonEntityTemp from "@/views/DMDComponent/commonEntityTemp.vue";
import InterfaceTemp from "@/views/DMDEntityInterface/interfaceTemp.vue";
import MenuTemp from "@/views/subApp/menuTemp.vue";
import LifeCycleTemp from "@/views/settingManage/msDrawerTemp/lifeCycleTemp.vue";
import CodeRulesTemp from "@/views/settingManage/msDrawerTemp/codeRulesTemp.vue";
import VersionRulesTemp from "@/views/settingManage/msDrawerTemp/versionRulesTemp.vue";
import JurisdictionTemp from "@/views/subApp/jurisdictionTemp.vue";
import ApplicationTemp from "@/views/DMDAppList/applicationTemp.vue";
import ConnectTemp from "@/views/connectManage/connectTemp.vue";
import ConditionTemp from "@/views/DMDCondition/conditionTemp.vue";
import TacticsTemp from "@/views/DMDTactics/tacticsTemp.vue";
import InterfaceHistoryTemp from "@/views/DMDEntityInterface/interfaceHistoryTemp.vue";
import ModelRelationTemp from "@/views/Model_Relation/modelRelationTemp.vue";
import DataSourceTemp from "@/views/dbbaseConfig/dataSourceTemp.vue";
import {PopupManager} from 'element-ui/src/utils/popup'
import DbbaseTemp from "@/views/dbbaseConfig/dbbaseTemp.vue";
import UserManageTemp from "@/views/userManage/userManageTemp.vue";
import RoleManageTemp from "@/views/roleManage/roleManageTemp.vue";
import TaskConfigTemp from "@/views/taskManage/taskConfigTemp.vue";
import EventManageTemp from "@/views/eventManage/eventManageTemp.vue";
import GlobalMethodTemp from "@/views/taskManage/globalMethodTemp.vue";
import DepartmentManageTemp from "@/views/departmentManage/departmentManageTemp.vue";
import UserGroupTemp from "@/views/userGroup/userGroupTemp.vue";
import CommonHistory from "@/views/DMDComponent/commonHistory.vue";
import QuickExtendTemp from "@/views/quickExtend/quickExtendTemp.vue";
import PhysicalTemp from "@/views/physicalData/physicalTemp.vue";
import LayoutEditTemp from "@/views/quickExtend/layoutEditTemp.vue";
import ViewListTemp from "@/views/viewList/viewListTemp.vue";
import NotificationTemplateTemp from "@/views/notificationTemplate/notificationTemplateTemp.vue";
import SignatureTemplateManageTemp from "@/views/signatureTemplateManage/signatureTemplateManageTemp.vue";
import OSSManageTemp from "@/views/OSSManage/OSSManageTemp.vue";
import SignatureViewTemp from "@/views/signatureTemplateManage/signatureViewTemp.vue";
import DepartmentManageFileTemp from "@/views/departmentManage/departmentManageFileTemp.vue";
import UserManageFileTemp from "@/views/userManage/userManageFileTemp.vue";
import TopMenuTemp from "@/views/top_menu/topMenuTemp.vue";

export default {
  name: "msDrawer",
  components: {
    TopMenuTemp,
    UserManageFileTemp,
    DepartmentManageFileTemp,
    SignatureViewTemp,
    OSSManageTemp,
    SignatureTemplateManageTemp,
    NotificationTemplateTemp,
    ViewListTemp,
    LayoutEditTemp,
    QuickExtendTemp,
    CommonHistory,
    UserManageTemp,
    RoleManageTemp,
    TaskConfigTemp,
    EventManageTemp,
    GlobalMethodTemp,
    DepartmentManageTemp,
    UserGroupTemp,
    ModelRelationTemp,
    InterfaceHistoryTemp,
    TacticsTemp,
    ConditionTemp,
    ApplicationTemp,
    JurisdictionTemp,
    VersionRulesTemp,
    CodeRulesTemp,
    LifeCycleTemp,
    MenuTemp,
    InterfaceTemp,
    CommonEntityTemp,
    PropertiesDefinedTemp,
    PropertiesClassifyTemp,
    UnitsManageTemp,
    EnumManageTemp,
    DbbaseTemp,
    DataSourceTemp,
    PhysicalTemp,
    ConnectTemp,
  },
  props: {
    visible: {
      type: Boolean,
      default: () => {
        return false;
      }
    },
    beforeClose: Function,
    tabList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    modal: {
      type: Boolean,
      default: () => {
        return false;
      }
    },
    title: "",
    idKey: {
      type: String,
      default: () => {
        return "oid"
      }
    },
    resize: {
      type: Boolean,
      default: () => {
        return true
      }
    }
  },
  data() {
    return {
      activeName: 0,
      fillScreen: false,

      width: "40%",

      move: false,

      msTabList: [],

      msIndex: PopupManager.nextZIndex()
    }
  },
  computed: {},
  methods: {
    ms$set(key, val) {
      this[key] = val;
    },
    /**
     * 点击单个组件编辑按钮时，修改tab状态
     * */
    viewToEdit(v) {
      v.type = "edit";
    },
    /**
     * 点击 右上方叉的时候关闭抽屉
     * */
    clickClose() {
      let done = () => {
        this.fillScreen = false;
        this.$emit("update:tabList", []);
        this.$emit("update:visible", false);
      }
      if (typeof this.beforeClose === "function") {
        this.beforeClose(done);
      } else {
        done();
      }
    },
    /**
     * 点击单个tab内的取消/保存时关闭当前tab页，如果只剩一个tab页则关闭抽屉
     * */
    removeThisTabs(v) {
      this.removeTab(v.row[this.idKey] + '-' + v.component);
    },
    removeTab(v) {
      let tabs = this.deepCopy(this.tabList);
      let tabList = [];
      tabList = tabs.filter(item => (item.row[this.idKey] + '-' + item.component) !== v);
      this.$emit("update:tabList", tabList)
      if (tabList.length === 0) {
        this.clickClose();
      } else {
        this.activeName = tabList[0].row[this.idKey] + '-' + tabList[0].component;
      }
    },

    /**
     * 给抽屉添加拖拽调整大小的事件
     * */
    dragMsDrawer() {
      let that = this;
      const drawerEle = document.querySelectorAll('.ms-drawer')
      let dragList = [];

      drawerEle.forEach((item, index) => {
        // 创建触发拖拽的元素
        const dragItem = document.createElement('div')
        dragItem.className = "drag-box-" + index;
        // 将元素放置到抽屉的左边边缘
        dragItem.style.cssText = 'height: 100%;width: 10px;cursor: w-resize;position: absolute;left: 0;top:0'
        item.append(dragItem)

        dragList.push(dragItem);
      })

      dragList.forEach(dragItem => {
        dragItem.onmousedown = () => {
          Object.assign(dragItem.parentNode.style, {transition: "all 0s"})
          // 拖拽时禁用文本选中
          document.body.style.userSelect = 'none'
          document.onmousemove = function (moveEvent) {
            // 获取鼠标距离浏览器右边缘的距离
            let realWidth = document.body.clientWidth - moveEvent.pageX
            const width40 = document.body.clientWidth * 0.4
            const width100 = document.body.clientWidth
            // 宽度不能大于浏览器宽度 80%，不能小于宽度的 40%
            realWidth = realWidth > width100 ? width100 : realWidth < width40 ? width40 : realWidth
            dragItem.parentNode.style.width = realWidth + 'px'
            that.width = realWidth + 'px'
          }
          document.onmouseup = function () {
            // 拖拽时结束时，取消禁用文本选中
            document.body.style.userSelect = 'initial'
            document.onmousemove = null
            document.onmouseup = null
            Object.assign(dragItem.parentNode.style, {transition: "all 0.4s"})
          }
        }
      })
    },

    /**
     * 已经显示的数据组件 不再重新渲染
     * */
    setTabItem() {
      //取出最新的oid集合
      let nvOid = this.tabList.map(item => (item.row[this.idKey] + '-' + item.component));
      //取出上一次的oid集合
      let ovOid = this.msTabList.map(item => (item.row[this.idKey] + '-' + item.component));
      //通过比较渲染新增的数据
      let indexList = [];
      nvOid.forEach((i, index) => {
        if (!ovOid.includes(i)) {
          indexList.push(index)
          this.activeName = i
        }
      });
      this.$nextTick(() => {
        let ref = this.$refs['com'];
        if (this.tabList.length > 0) {
          this.tabList.forEach((item, index) => {
            if (indexList.includes(index) && ref[index]) {
              if (ref[index][item.type]) {
                ref[index][item.type](item.row);
              } else {
                throw new Error(`找不到方法 ${item.type}`);
              }
            }
          })
        }
      })

      this.msTabList = this.deepCopy(this.tabList);
    }
  },
  watch: {
    visible: {
      handler(v) {
        if (v) {
          this.$nextTick(() => {
            this.width = "50%";
            this.dragMsDrawer();
          })
        } else {
          this.$emit("update:tabList", [])
          this.msTabList = [];
          this.activeName = 0;
        }
      },
      immediate: true,
      deep: true
    },
    tabList: {
      handler(nv) {
        if (this.visible) {
          // 第一次打开默认选中 第一条数据的tab
          this.activeName = this.activeName === 0 ? (nv[0].row[this.idKey] + '-' + nv[0].component) : this.activeName;
          this.setTabItem();
        }
      },
      immediate: true,
      deep: true
    }
  }
}
</script>
<style scoped lang="scss">
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  right: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 998;
  transition: all .4s;
}

.ms-drawer {
  height: 100%;
  position: fixed;
  right: 0;
  top: 0;
  background: #fff;
  z-index: 999;
  box-shadow: 0 2px 15px 0 rgba(0, 0, 0, .3);
  transition: all .4s;
}


$mdHeader: 50px;
$mdTags: 40px;
$mdBtns: 36px;
.md-drawer {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: calc(100% - 10px);
  width: 100%;
  padding: 0 10px;
  box-sizing: border-box;

  .close {
    position: absolute;
    top: 15px;
    right: 10px;
    font-size: 20px;
    cursor: pointer;

    > i {
      font-size: 18px;

      &:hover {
        color: #1e9fff;
      }
    }

    i:last-child {
      font-size: 20px;
    }

    > i + i {
      margin-left: 10px;
    }
  }

  .md-header {
    width: calc(100% + 20px);
    height: $mdHeader;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
    margin-left: -10px;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .md-tags {
      width: calc(100% - 100px);
      height: 100%;
      padding-left: 10px;

      ::v-deep .el-tabs {
        height: 100%;

        .el-tabs__header {
          border: none;
          margin: 0;
          height: 100%;

          .el-tabs__nav-wrap {
            height: 100%;

            .el-tabs__nav-scroll {
              height: 100%;

              .el-tabs__nav {
                border: none;
                height: 100%;

                .el-tabs__item {
                  border: none;
                  height: 100%;
                  line-height: $mdHeader;
                }

                .is-active {
                  border-bottom: 2px solid #1e9fff;
                  padding: 0 10px;
                }
              }
            }

            .el-tabs__nav-prev {
              line-height: $mdHeader;
            }

            .el-tabs__nav-next {
              line-height: $mdHeader;
            }
          }
        }
      }
    }
  }

  .md-container {
    width: 100%;
    height: calc(100% - #{$mdHeader} - #{$mdBtns} - 30px);
    overflow-y: scroll;
    overflow-x: hidden;
  }

  .md-btns {
    height: $mdBtns;
    width: 100%;
  }
}

/*
::v-deep .el-drawer__wrapper {
  width: 80%;
}*/
</style>

<style lang="scss">
$mdBtns: 36px;
.md-component-btns {
  height: $mdBtns;
  width: calc(100% - 20px);
  position: absolute;
  bottom: 10px;
  text-align: right;
}

.column-btn {
  color: #1e9fff;
  cursor: pointer;
}
</style>
